/*
 * @Copyright: 2023 - 2023 www.hoperun.com Inc. All rights reserved.
 */

package com.lifeservice.wxapi;

import com.lifeservice.common.config.LifeServiceConfig;
import com.lifeservice.common.core.domain.AjaxResult;
import com.lifeservice.common.core.redis.RedisCache;
import com.lifeservice.common.utils.DateUtils;
import com.lifeservice.common.utils.SecurityUtils;
import com.lifeservice.common.utils.StringUtils;
import com.lifeservice.console.domain.LifeSchedule;
import com.lifeservice.console.domain.LifeSupplierInfo;
import com.lifeservice.console.domain.LifeWorkClass;
import com.lifeservice.console.domain.ScheduInfo;
import com.lifeservice.console.domain.appvo.AppBaseQueryVo;
import com.lifeservice.console.mapper.LifeScheduleMapper;
import com.lifeservice.console.mapper.LifeSupplierInfoMapper;
import com.lifeservice.console.mapper.LifeWorkClassMapper;
import com.lifeservice.util.LifeServiceConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liu_yifeng
 * @function 供应商信息wx接口
 * @date 2023/2/27 10:17
 */
@RestController
@RequestMapping("/wx/supplier")
@Slf4j
public class WxSupplierController {

    @Autowired
    private LifeSupplierInfoMapper lifeSupplierInfoMapper;

    @Autowired
    private LifeScheduleMapper lifeScheduleMapper;

    @Autowired
    private LifeWorkClassMapper lifeWorkClassMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private LifeServiceConfig lifeServiceConfig;

    @PostMapping("/list")
    public AjaxResult listForApp(@RequestBody AppBaseQueryVo appBaseQueryVo) {
        List<LifeSupplierInfo> list = new LinkedList<>();
        String buildingId = appBaseQueryVo.getBuildingId();
        // 如果没有大厦id，则返回空
        if (StringUtils.isEmpty(buildingId)) {
            return AjaxResult.success(list);
        }
        LifeSchedule querySchedule = new LifeSchedule();
        querySchedule.setBuildId(buildingId);
        List<LifeSchedule> scheduleList = lifeScheduleMapper.selectLifeScheduleList(querySchedule);
        if (StringUtils.isEmpty(scheduleList)) {
            return AjaxResult.success(list);
        }
        Map<String, LifeSchedule> scheduleMap = scheduleList.stream()
                .collect(Collectors.toMap(LifeSchedule::getSupplierId, v -> v, (p1, p2) -> p1));
        Set<String> supplierIdList = scheduleList.stream().map(LifeSchedule::getSupplierId).collect(Collectors.toSet());
        LifeSupplierInfo query = new LifeSupplierInfo();
        query.setServiceId(appBaseQueryVo.getServiceId());
        query.setIds(supplierIdList);
        query.setQueryParam(SecurityUtils.allLikeParam(appBaseQueryVo.getQueryParam()));
        List<LifeSupplierInfo> lifeSupplierInfoList = lifeSupplierInfoMapper.selectLifeSupplierInfoList(query);
        if (StringUtils.isEmpty(lifeSupplierInfoList)) {
            return AjaxResult.success(list);
        }
        lifeSupplierInfoList.stream().forEach(lifeSupplierInfo -> {
            String workTime = "";
            String sleepTime = "";
            LifeSchedule schedule = scheduleMap.get(lifeSupplierInfo.getId());
            workTime = schedule.getWorkStartTime() + "-" + schedule.getWorkEndTime();
            sleepTime = schedule.getSleepStartTime() + "-" + schedule.getSleepEndTime();
            lifeSupplierInfo.setWorkTimeDesc("服务时间：" + workTime + "，休息时间：" + sleepTime);
            list.add(lifeSupplierInfo);
        });
        return AjaxResult.success(list);
    }

    @PostMapping("/worklist")
    public AjaxResult workList(@RequestBody AppBaseQueryVo appBaseQueryVo) {
        List<ScheduInfo> scheduleInfoList = new LinkedList<>();
        LifeSchedule querySchedule = new LifeSchedule();
        querySchedule.setSupplierId(appBaseQueryVo.getSupplierId());
        querySchedule.setBuildId(appBaseQueryVo.getBuildingId());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, lifeServiceConfig.getDefaultQueryDays());
        querySchedule.setEndDay(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, calendar.getTime()));
        List<LifeSchedule> schedules = lifeScheduleMapper.selectLifeScheduleList(querySchedule);
        for (LifeSchedule lifeSchedule : schedules) {
            ScheduInfo info = new ScheduInfo();
            String serveDay = lifeSchedule.getServeDay();
            Calendar caServeDay = Calendar.getInstance();
            caServeDay.setTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD, serveDay));
            Calendar nowDay = Calendar.getInstance();
            nowDay.setTime(new Date());
            nowDay.set(Calendar.HOUR_OF_DAY, 0);
            nowDay.set(Calendar.MINUTE, 0);
            nowDay.set(Calendar.SECOND, 0);
            nowDay.set(Calendar.MILLISECOND, 0);
            if (caServeDay.before(nowDay)) {
                log.info("serve day {} is before nowday dont need it!", serveDay);
                continue;
            }
            String dayString = "";
            if (caServeDay.get(Calendar.YEAR) == nowDay.get(Calendar.YEAR) && caServeDay.get(Calendar.MONTH) == nowDay.get(Calendar.MONTH) && caServeDay.get(Calendar.DATE) == nowDay.get(Calendar.DATE)) {
                dayString = "今天 " + (caServeDay.get(Calendar.MONTH) + 1) + "-" + caServeDay.get(Calendar.DATE);
            } else {
                String month = (caServeDay.get(Calendar.MONTH) + 1) < 10 ? "0" + (caServeDay.get(Calendar.MONTH) + 1) : "" + (caServeDay.get(Calendar.MONTH) + 1);
                String day = caServeDay.get(Calendar.DATE) < 10 ? "0" + caServeDay.get(Calendar.DATE) : "" + caServeDay.get(Calendar.DATE);
                dayString = lifeSchedule.getServeWeek() + " " + month + "-" + day;
            }
            info.setDay(dayString);
            info.setDayForSort(serveDay);
            info.setWeek(lifeSchedule.getServeWeek());
            String scheduleId = lifeSchedule.getId();
            // 排班计划先取redis，没有再取数据库
            String workClassCacheKey = LifeServiceConstants.WORK_CLASS_BY_SCHEID_CACHE_PREFIX + scheduleId;
            List<LifeWorkClass> lifeWorkClassList = new LinkedList<>();
            if (StringUtils.isEmpty(redisCache.getCacheList(workClassCacheKey))) {
                LifeWorkClass lifeWorkClass = new LifeWorkClass();
                lifeWorkClass.setScheduleId(scheduleId);
                lifeWorkClassList = lifeWorkClassMapper.selectLifeWorkClassList(lifeWorkClass);
                redisCache.setCacheList(workClassCacheKey, lifeWorkClassList);
            } else {
                lifeWorkClassList = redisCache.getCacheList(workClassCacheKey);
            }
            // 如果是当天的排班列表，只返回当前时间之后的排班
            if (dayString.startsWith("今天")) {
                List<LifeWorkClass> dealList = new ArrayList<>(lifeWorkClassList);
                for (LifeWorkClass todayWork : lifeWorkClassList) {
                    String workTime = todayWork.getWorkTime();
                    String workStartTime = workTime.split("-")[1];
                    Integer hour = Integer.parseInt(workStartTime.split(":")[0]);
                    Integer minute = Integer.parseInt(workStartTime.split(":")[1]);
                    Calendar compareNow = Calendar.getInstance();
                    compareNow.setTime(new Date());
                    Integer nowHour = compareNow.get(Calendar.HOUR_OF_DAY);
                    Integer nowMinute = compareNow.get(Calendar.MINUTE);
                    if (nowHour > hour || (nowHour == hour && nowMinute > minute)) {
                        dealList.remove(todayWork);
                    }
                }
                lifeWorkClassList = dealList;
            }
            if (StringUtils.isEmpty(lifeWorkClassList)) {
                continue;
            }
            lifeWorkClassList = lifeWorkClassList.stream().sorted(Comparator.comparing(LifeWorkClass::getWorkClass, Comparator.comparingInt(Integer::parseInt))).collect(Collectors.toList());
            // 区分上午下午
            List<LifeWorkClass> amWorkClassList = new LinkedList<>();
            List<LifeWorkClass> pmWorkClassList = new LinkedList<>();
            for (LifeWorkClass toDoWorkClass : lifeWorkClassList) {
                String workTime = toDoWorkClass.getWorkTime();
                String workStartTime = workTime.split("-")[1];
                Integer hour = Integer.parseInt(workStartTime.split(":")[0]);
                Integer minute = Integer.parseInt(workStartTime.split(":")[1]);
                if (hour > 12 || (hour == 12 && minute > 0)) {
                    pmWorkClassList.add(toDoWorkClass);
                } else {
                    amWorkClassList.add(toDoWorkClass);
                }
            }
            info.setAmWorkClassList(amWorkClassList);
            Integer amStock = amWorkClassList.size() == 0 ? -1 : amWorkClassList.stream().map(LifeWorkClass::getStock).reduce(0, Integer::sum);
            info.setAmHasStock(amStock);
            info.setPmWorkClassList(pmWorkClassList);
            Integer pmStock = pmWorkClassList.size() == 0 ? -1 : pmWorkClassList.stream().map(LifeWorkClass::getStock).reduce(0, Integer::sum);
            info.setPmHasStock(pmStock);
            scheduleInfoList.add(info);
        }
        scheduleInfoList = scheduleInfoList.stream().sorted(Comparator.comparing(ScheduInfo::getDayForSort, Comparator.nullsFirst(Comparator.naturalOrder()))).collect(Collectors.toList());
        Map<String, ScheduInfo> infoMapByDateMap = scheduleInfoList.stream()
                .collect(Collectors.toMap(ScheduInfo::getDayForSort, v -> v, (p1, p2) -> p1));
        List<ScheduInfo> finalList = new LinkedList<>();
        // 补齐没有排班的日子对象给前端
        for (int i = 0; i <= lifeServiceConfig.getDefaultQueryDays(); i++) {
            Calendar calendarLast = Calendar.getInstance();
            calendarLast.add(Calendar.DATE, i);
            String dateS = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, calendarLast.getTime());
            ScheduInfo sc = infoMapByDateMap.get(dateS);
            if (null == sc) {
                sc = new ScheduInfo();
                sc.setDayForSort(dateS);
                sc.setWeek(LifeServiceConstants.getWeekConvertMap().get(calendarLast.get(Calendar.DAY_OF_WEEK)));
                if (sc.getWeek().equals("周六") || sc.getWeek().equals("周日")) {
                    log.info("fill empty workclass skip zhouliu  zhouri");
                    continue;
                }
                sc.setAmHasStock(-1);
                sc.setPmHasStock(-1);
                sc.setDay(sc.getWeek() + " " + dateS.substring(5, 10));
            }
            finalList.add(sc);
        }
        return AjaxResult.success(finalList);
    }
}
